"""
进程API路由
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from app.core.deps import get_db
from app.crud import process as crud_process
from app.schemas.process import Process, ProcessCreate
from typing import List
from app.schemas.response import ApiResponse

router = APIRouter()

@router.get("/test", response_model=ApiResponse)
def test_processes():
    """测试进程API"""
    return ApiResponse(
        success=True,
        data={"message": "进程API正常工作"},
        message="测试成功"
    )

@router.get("/", response_model=ApiResponse)
def read_processes(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db)
):
    """获取进程列表"""
    processes = crud_process.get_all_processes(db, skip=skip, limit=limit)
    process_list = [Process.model_validate(process) for process in processes]
    return ApiResponse(
        success=True,
        data=process_list,
        message="进程列表获取成功"
    )

@router.get("/{process_id}", response_model=ApiResponse)
def read_process(
    process_id: int,
    db: Session = Depends(get_db)
):
    """根据ID获取进程详情"""
    db_process = crud_process.get_process_by_id(db, process_id=process_id)
    if db_process is None:
        return ApiResponse(
            success=False,
            data=None,
            message="进程不存在"
        )
    process = Process.model_validate(db_process)
    return ApiResponse(
        success=True,
        data=process,
        message="进程详情获取成功"
    )

@router.get("/machine/{machine_id}", response_model=ApiResponse)
def read_processes_by_machine(
    machine_id: int,
    limit: int = Query(100, description="返回进程数量限制"),
    db: Session = Depends(get_db)
):
    """根据机器ID获取进程列表"""
    processes = crud_process.get_processes_by_machine_id_limit(db, machine_id=machine_id, limit=limit)
    process_list = [Process.model_validate(process) for process in processes]
    return ApiResponse(
        success=True,
        data=process_list,
        message="机器进程列表获取成功"
    )

@router.post("/", response_model=ApiResponse)
def create_process(
    process: ProcessCreate,
    db: Session = Depends(get_db)
):
    """创建进程"""
    created_process = crud_process.create_process(db, process_data=process.dict())
    process_schema = Process.model_validate(created_process)
    return ApiResponse(
        success=True,
        data=process_schema,
        message="进程创建成功"
    )

@router.delete("/{process_id}", response_model=ApiResponse)
def delete_process(
    process_id: int,
    db: Session = Depends(get_db)
):
    """删除进程"""
    result = crud_process.delete_process(db, process_id=process_id)
    if not result:
        return ApiResponse(
            success=False,
            data=False,
            message="进程不存在"
        )
    return ApiResponse(
        success=True,
        data=True,
        message="进程删除成功"
    )